package com.talking.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.github.dhaval2404.imagepicker.ImagePicker;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsBuildBitmapOption;
import com.huawei.hms.ml.scan.HmsScan;
import com.talking.App;
import com.talking.R;
import com.talking.databinding.ActivityAccountBinding;
import com.talking.model.Http;
import com.talking.presenter.UserPresenter;
import com.talking.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AccountActivity extends AppCompatActivity {
    private ActivityAccountBinding binding;
    private ActivityResultLauncher<Intent> launcher;
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityAccountBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        UserPresenter.getUserByAccount(App.sp.getString("account", ""),null, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                runOnUiThread(() -> {
                    try {
                        JSONObject jo = new JSONObject(response.body().string());
                        AccountActivity.this.setTitle("账户："+jo.getString("account"));
                        if (!jo.isNull("nickname")){
                            binding.accountNickname.setText(jo.getString("nickname"));
                            Glide.with(AccountActivity.this).load(Http.BASE_URL+jo.getString("iconUrl")).apply(Utils.getGlideOption()).placeholder(R.drawable.loading).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.accountImageView);
                        }
                        Bitmap qrBitmap = ScanUtil.buildBitmap("add:"+jo.getString("account"), HmsScan.QRCODE_SCAN_TYPE, 400, 400, new HmsBuildBitmapOption.Creator().setBitmapBackgroundColor(Color.WHITE).setBitmapColor(Color.rgb(240,99,101)).setBitmapMargin(3).create());
                        binding.accountQrcode.setImageBitmap(qrBitmap);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
        binding.accountEmail.setText(App.sp.getString("email","邮箱错误"));
        binding.accountImageView.setOnClickListener(view -> {
            if (Utils.hasExternalStoragePermission(this)){
                ImagePicker.with(this).cropSquare().compress(1024).maxResultSize(1080, 1080).saveDir(getExternalCacheDir().toString() + "icon").createIntent(intent -> {
                    launcher.launch(intent);
                    return null;
                });
            }else {
                Utils.requestPermission(this);
            }
        });
        launcher=registerForActivityResult(new StartActivityForResult(), result -> {
            int code=result.getResultCode();
            if (code == RESULT_OK) {
                Uri uri = result.getData().getData();
                File file = new File(uri.getPath());
                Glide.with(this).load(uri).apply(Utils.getGlideOption()).placeholder(R.drawable.loading).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.accountImageView);
                UserPresenter.uploadIcon("user/uploadIconByEmail/?email="+binding.accountEmail.getText().toString(), file, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        file.deleteOnExit();
                    }
                });
            } else if (code == ImagePicker.RESULT_ERROR) {
                Utils.toast(ImagePicker.getError(result.getData()));
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_account, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()== R.id.menu_save){
            if (!binding.accountNickname.getText().toString().equals("")){
               UserPresenter.modifyByEmail(App.sp.getString(
                       "email", ""),
                       App.sp.getString("password", ""),
                       binding.accountNickname.getText().toString(), new Callback() {
                   @Override
                   public void onFailure(@NotNull Call call, @NotNull IOException e) {
                       runOnUiThread(() -> Utils.toast(e.toString()));
                   }
                   @Override
                   public void onResponse(@NotNull Call call, @NotNull Response response) {
                       runOnUiThread(() -> {
                           try {
                               String str=response.body().string();
                               if (str.equals("保存完毕")){
                                  Utils.toast("保存完毕");
                                  AccountActivity.this.setResult(2);
                                  AccountActivity.this.finish();
                              }else {
                                  Utils.toast(str);
                              }
                           } catch (Exception e) {
                               e.printStackTrace();
                           }
                       });
                   }
               });
            }
        }
        return true;
    }
    public void logout(View view){
        AccountActivity.this.setResult(3);
        AccountActivity.this.finish();
    }
}